package angels.client.Tasks;
import java.net.HttpURLConnection;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import angels.client.Entities.User;
import angels.client.Helpers.JSONHelper;
import angels.client.Listeners.UserListener;
import angels.client.Services.UserService;

public class GetUserTask extends TimerTask {
	private DefaultHttpClient client;
	private final UserService service;
	private final String username;
	private final UserListener listener;
	
	//Constructor
	public GetUserTask(UserService service,String username,UserListener listener) {
		this.service = service;
		this.username=username;
		this.listener=listener;
		// set parameters
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        client = new DefaultHttpClient(httpParameters);
	}
	
	@Override
    public void run() {
		try {
			String path=service.getUserURL(username);
			HttpGet request = new HttpGet(path);
			HttpResponse response = client.execute(request);
			
			if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK)
			    return;
			
			JSONObject json_response;
						
			User user=null;
						
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
				json_response = JSONHelper.parseJSONResponse(response);
				user=new User(json_response);
			} 
			// notify service of results
			if (user!=null)
			{
				service.notifyTraffic(user,listener);
			}
			service.notifyTraffic(user,listener);
		} catch (Exception e) {}
	}
}